package com.smartrobot.smartrobot.activity;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.application.SmartRobotApplication;
import com.github.siyamed.shapeimageview.CircularImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.smartrobot.smartrobot.Common.Common;
import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.adapter.SocialListViewAdapter;
import com.smartrobot.smartrobot.circle.FriendList;
import com.smartrobot.smartrobot.util.FileUtil;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.ImageLoaderApi;
import com.smartrobot.smartrobot.util.ImageUtil;
import com.smartrobot.smartrobot.util.PictureFromCammera;
import com.smartrobot.smartrobot.util.QRCode;
import com.smartrobot.smartrobot.util.User;
import com.smartrobot.smartrobot.view.ToastCustom;

import com.smartrobot.smartrobot.websocket.Util;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2015/1/13.
 */
public class PersonalMessageActivity extends Activity implements View.OnClickListener{

    private ImageView qrImage,back;
    private CircularImageView head;
    private TextView nickName,name,gender,age,role,organ,phone,say,address,logout,url;
    private ProgressBar progressBar;
    private Bitmap headBitmap;
    private User user;
    private RelativeLayout layoutHead,layoutNickName,layoutName,layoutPhone,layoutGender,layoutAge,layoutRole,layoutQrcode,layoutOrgan,layoutSay,layoutAddress,backControl;
    private String path;
    private ImageLoader imageLoader;

    public static PersonalMessageActivity instance;


    private Map<String,String> map;
    private PersonlMessageHandler handler;
    private final int HANDLER_DATA_NEED_RESET = 1444;
    private final int HANDLER_DATA_RESET = 1445;
    private final int RESOULT_RETURN = 1446;
    private final int RESOULT_RETURN_CREATE = 1447;
    private final int RESOULT_UP_MASTER = 1448;
    private final int RESOULT_UP_HAIRRESET = 1449;


    private boolean isSetting;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null){
            throw new NullPointerException();
        }

        instance = this;
        isSetting = false;
        imageLoader = ImageLoader.getInstance();
        user = User.getInstance();
        map = new HashMap<String,String>();
        handler = new PersonlMessageHandler();
        HttpUtil.init(getApplicationContext());
        ImageLoaderApi.initImageLoaderApi(getApplicationContext());

        if(user.getRole().equals("客户")){//这里没有处理未登录的问题
            this.setContentView(R.layout.page_personal_msg_user);
            initUser();
        }else{
            this.setContentView(R.layout.page_personal_msg_hairreset);
            initHairReset();
        }


        if(!user.getHead().contains("/storage"))
             imageLoader.displayImage(Common.baseUrl+user.getHead(),head,ImageLoaderApi.getOptions());
        else
        {
            Bitmap bitmap = BitmapFactory.decodeFile(user.getHead());
            head.setImageBitmap(bitmap);

        }

        layoutHead = (RelativeLayout)findViewById(R.id.personal_message_head_layout);
        layoutNickName = (RelativeLayout)findViewById(R.id.personal_message_nickname_layout);
        layoutName = (RelativeLayout)findViewById(R.id.personal_message_realname_layout);
        layoutPhone = (RelativeLayout)findViewById(R.id.personal_message_phone_layout);
        layoutGender = (RelativeLayout)findViewById(R.id.personal_message_sex_layout);
        layoutAge = (RelativeLayout)findViewById(R.id.personal_message_age_layout);
        layoutRole = (RelativeLayout)findViewById(R.id.personal_message_role_layout);
        layoutQrcode = (RelativeLayout)findViewById(R.id.personal_message_qrcode_layout);
        layoutSay = (RelativeLayout)findViewById(R.id.personal_message_say_layout);
        layoutAddress  = (RelativeLayout)findViewById(R.id.personal_message_address_layout);
        progressBar = (ProgressBar)findViewById(R.id.presonnal_progress);
        back = (ImageView)findViewById(R.id.message_back);
        logout =(TextView)findViewById(R.id.message_logout);


        layoutHead.setOnClickListener(this);
        layoutNickName.setOnClickListener(this);
        layoutName.setOnClickListener(this);
        layoutPhone.setOnClickListener(this);
        layoutGender.setOnClickListener(this);
        layoutAge.setOnClickListener(this);
        layoutRole.setOnClickListener(this);
        layoutQrcode.setOnClickListener(this);
        layoutSay.setOnClickListener(this);
        layoutAddress.setOnClickListener(this);
        back.setOnClickListener(this);
        logout.setOnClickListener(this);

        setQRImage();


    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    void initHairReset(){

        head = (CircularImageView)findViewById(R.id.hairreset_head);
        qrImage = (ImageView)findViewById(R.id.hairreset_qrcode);
        nickName  = (TextView)findViewById(R.id.hairreset_nickName);
        name = (TextView)findViewById(R.id.hairreset_name);
        gender = (TextView)findViewById(R.id.hairreset_gender);
        age = (TextView)findViewById(R.id.hairreset_age);
        role = (TextView)findViewById(R.id.hairreset_role);
        organ = (TextView)findViewById(R.id.hairreset_organ);
        phone = (TextView)findViewById(R.id.hairreset_phone);
        say = (TextView)findViewById(R.id.hairreset_say);
        address = (TextView)findViewById(R.id.hairreset_address);
        layoutOrgan = (RelativeLayout)findViewById(R.id.personal_message_belongStore_layout);
        backControl = (RelativeLayout)findViewById(R.id.person_backControl);
        url = (TextView)findViewById(R.id.pseronal_url);

        nickName.setText(user.getNickname());
        name.setText(user.getName());
        gender.setText(user.getSex());
        age.setText(user.getAge());
        role.setText(user.getRole());
        organ.setText(user.getBarberName());
        phone.setText(user.getPhone());
        say.setText(user.getSignature());
        address.setText(user.getAddress());
        layoutOrgan.setOnClickListener(this);
        head.setOnClickListener(this);


        if(user.getRole().equals("店主"))
        {
            backControl.setVisibility(View.VISIBLE);
            url.setText(Common.managerUrl);
        }

    }

    void initUser(){

        head = (CircularImageView)findViewById(R.id.user_Head);
        qrImage = (ImageView)findViewById(R.id.user_Qrcode);
        nickName  = (TextView)findViewById(R.id.user_NickName);
        name = (TextView)findViewById(R.id.user_Name);
        gender = (TextView)findViewById(R.id.user_Gender);
        age = (TextView)findViewById(R.id.user_Age);
        role = (TextView)findViewById(R.id.user_Role);
        phone = (TextView)findViewById(R.id.user_Phone);
        say = (TextView)findViewById(R.id.user_say);
        address = (TextView)findViewById(R.id.user_address);

        nickName.setText(user.getNickname());
        name.setText(user.getName());
        gender.setText(user.getSex());
        age.setText(user.getAge());
        role.setText(user.getRole());
        phone.setText(user.getPhone());
        say.setText(user.getSignature());
        address.setText(user.getAddress());
        head.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        final Intent intent = new Intent();

        switch (view.getId()){

            case R.id.message_back:
                this.finish();
               break;

            case R.id.message_logout:

                AlertDialog dialog3 = new AlertDialog.Builder(PersonalMessageActivity.this)
                        .setTitle("是否要注销？")
                        .setMessage("选择注销，将会消除自动登录和接收信息推送的功能，除非下次登录！")
                        .setPositiveButton("确定",new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                user.reSert();
                                Intent intent = new Intent();
                                intent.setClass(PersonalMessageActivity.this,LoginActivity.class);
                                startActivity(intent);
                                if(MainActivity.instance != null)
                                {
                                    MainActivity.instance.finish();
                                }
                                HttpUtil.apiLogout();
                                SmartRobotApplication.getInstance().logout(null);


                                Util.stopWebsocketServer();

                                PersonalMessageActivity.this.finish();


                            }
                        })
                        .setNegativeButton("取消",new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).show();

                dialog3.setCanceledOnTouchOutside(true);

                break;

            case R.id.personal_message_head_layout:

                Log.d("===============>","重选头像");

                // type == 2

                AlertDialog dialog = new AlertDialog.Builder(PersonalMessageActivity.this)
                        .setTitle("选择")
                        .setItems(R.array.photoMenu,
                                new AlertDialog.OnClickListener() {

                                    public void onClick(DialogInterface dialog,int which) {
                                        switch (which) {
                                            case 0://通过照相机获取图片
                                                path = ImageUtil.getCameraPic(PersonalMessageActivity.this, ImageUtil.IMAGE_FROM_CAMMERA);
                                                break;
                                            case 1://通过打开文件获取图片
                                                ImageUtil.getDirPic(PersonalMessageActivity.this,ImageUtil.IMAGE_FROM_FILE);
                                                break;
                                        }
                                    }
                                }).show();
                dialog.setCanceledOnTouchOutside(true);

                break;

            case R.id.personal_message_nickname_layout:

                Log.d("===============>","重选昵称");
                intent.putExtra("type","1");
                intent.putExtra("key","昵称");
                intent.putExtra("value",nickName.getText().toString());
                intent.setClass(PersonalMessageActivity.this,ResetPersonMessageActivity.class);
                startActivityForResult(intent, RESOULT_RETURN);

                break;

            case R.id.personal_message_realname_layout:

                Log.d("===============>","重选真实姓名");
                intent.putExtra("type","5");
                intent.putExtra("key","真实姓名");
                intent.putExtra("value",name.getText().toString());
                intent.setClass(PersonalMessageActivity.this,ResetPersonMessageActivity.class);
                startActivityForResult(intent, RESOULT_RETURN);
                break;


            case R.id.personal_message_age_layout:

                Log.d("===============>","重选年龄");
                intent.putExtra("type","7");
                intent.putExtra("key","年龄");
                intent.putExtra("value",age.getText().toString());
                intent.setClass(PersonalMessageActivity.this,ResetPersonMessageActivity.class);
                startActivityForResult(intent, RESOULT_RETURN);
                break;

            case R.id.personal_message_say_layout:
                Log.d("===============>","重选个人签名");
                intent.putExtra("type","4");
                intent.putExtra("key","个人签名");
                intent.putExtra("value",say.getText().toString());
                intent.setClass(PersonalMessageActivity.this,ResetPersonMessageActivity.class);
                startActivityForResult(intent, RESOULT_RETURN);
                break;

            case R.id.personal_message_address_layout:

                Log.d("===============>","重选个人地址");
                intent.putExtra("type","6");
                intent.putExtra("key","地址");
                intent.putExtra("value",address.getText().toString());
                intent.setClass(PersonalMessageActivity.this,ResetPersonMessageActivity.class);
                startActivityForResult(intent, RESOULT_RETURN);
                //type == 6

                break;

            case R.id.personal_message_sex_layout:

                Log.d("===============>","重选性别");
                AlertDialog dialog1 = new AlertDialog.Builder(PersonalMessageActivity.this)
                        .setTitle("选择性别")
                        .setItems(R.array.sexMenu,
                                new AlertDialog.OnClickListener() {

                                    public void onClick(DialogInterface dialog,int which) {
                                        Message msg = new Message();
                                        switch (which) {
                                            case 0://选择男性别

                                                map.put("key","3");
                                                map.put("value","男");
                                                map.put("file","");
                                                msg.what = HANDLER_DATA_NEED_RESET;
                                                //type = 3
                                                break;
                                            case 1://选择女性别
                                                map.put("key","3");
                                                map.put("value","女");
                                                map.put("file","");
                                                msg.what = HANDLER_DATA_NEED_RESET;
                                                break;
                                        }
                                        handler.sendMessage(msg);

                                    }
                                }).show();
                dialog1.setCanceledOnTouchOutside(true);

                break;

            case R.id.personal_message_role_layout:

                int menu = 0;

                if(user.getRole().equals("客户"))
                    menu = R.array.upToHairreset;
                else
                    menu = R.array.upToMaster;



                AlertDialog dialog2 = new AlertDialog.Builder(PersonalMessageActivity.this)
                        .setTitle("升级")
                        .setItems(menu , new AlertDialog.OnClickListener() {

                                    public void onClick(DialogInterface dialog,int which) {
                                        Message msg = new Message();
                                        switch (which) {
                                            case 0://选择升级成店主


                                                if(!user.getBarberId().equals("未填写")){//有直属理发师提示
                                                    AlertDialog dialog3 = new AlertDialog.Builder(PersonalMessageActivity.this)
                                                            .setTitle("提示：")
                                                            .setMessage("您具有直属理发师，若是升级为店主将不在所属于这个理发师并将失去该理发师的圈子好友,确定要升级?")
                                                            .setPositiveButton("确定",new DialogInterface.OnClickListener(){
                                                                @Override
                                                                public void onClick(DialogInterface dialogInterface, int i) {

                                                                    Intent intent1 = new Intent();
                                                                    intent1.setClass(PersonalMessageActivity.this,CretaOrganActivity.class);
                                                                    startActivityForResult(intent1, RESOULT_UP_MASTER);


                                                                }
                                                            })
                                                            .setNegativeButton("取消",new DialogInterface.OnClickListener(){
                                                                @Override
                                                                public void onClick(DialogInterface dialogInterface, int i) {

                                                                }
                                                            }).show();

                                                    dialog3.setCanceledOnTouchOutside(true);


                                                }else{//若是没有直属理发师，就直接跳转

                                                    Intent intent1 = new Intent();
                                                    intent1.setClass(PersonalMessageActivity.this,CretaOrganActivity.class);
                                                    startActivityForResult(intent1, RESOULT_UP_MASTER);

                                                }



                                                break;
                                            case 1://选择升级成理发师

                                                if(!user.getBarberId().equals("未填写")){//有直属理发师提示
                                                    AlertDialog dialog3 = new AlertDialog.Builder(PersonalMessageActivity.this)
                                                            .setTitle("提示：")
                                                            .setMessage("您具有直属理发师，若是升级为理发师将不在所属于原来的理发师并将失去该理发师的圈子好友,确定要升级?")
                                                            .setPositiveButton("确定",new DialogInterface.OnClickListener(){
                                                                @Override
                                                                public void onClick(DialogInterface dialogInterface, int i) {

                                                                    Intent intent = new Intent();
                                                                    intent.setClass(PersonalMessageActivity.this, UptoHairResetActivity.class);
                                                                    startActivityForResult(intent, RESOULT_UP_HAIRRESET);


                                                                }
                                                            })
                                                            .setNegativeButton("取消",new DialogInterface.OnClickListener(){
                                                                @Override
                                                                public void onClick(DialogInterface dialogInterface, int i) {

                                                                }
                                                            }).show();

                                                    dialog3.setCanceledOnTouchOutside(true);


                                                }else{//若是没有直属理发师，就直接跳转

                                                    Intent intent = new Intent();
                                                    intent.setClass(PersonalMessageActivity.this, UptoHairResetActivity.class);
                                                    startActivityForResult(intent, RESOULT_UP_HAIRRESET);

                                                }



                                                break;
                                        }
                                        handler.sendMessage(msg);

                                    }
                                }).show();
                dialog2.setCanceledOnTouchOutside(true);
                Log.d("===============>","重选角色");
                break;

            case R.id.personal_message_qrcode_layout:

                Log.d("===============>","重选二维码");
                Intent intent1 = new Intent();
                intent1.setClass(this, ShowBigQrActivity.class);
                startActivity(intent1);

                break;

            case R.id.personal_message_belongStore_layout:

                Log.d("===============>","重选所属理发店");
                break;

            case R.id.hairreset_head:
            case R.id.user_Head:

                Log.d("===============>","c");
                Intent intent2 = new Intent();
                intent2.setClass(this, ShowBigQrActivity.class);
                intent2.putExtra("head","not null");
                startActivity(intent2);


                break;


        }
    }


    public Drawable getHeadPic(){

        return head.getBackground();

    }

    // 处理返回结果
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == ImageUtil.IMAGE_FROM_CAMMERA) {// 通过照相机获取图片
            if (resultCode == RESULT_OK) { // 成功获得图片
                if(path != null && !path.equals(""))
                {
                    headBitmap = PictureFromCammera.scaleBitmap(path);
//                    head.setImageBitmap(headBitmap);

                    // 头像的名字
                    String fileName = FileUtil.headName;
                    //保存的路径
                    String filePath = FileUtil.PHONE_DIR_INNER + FileUtil.PICTURE
                            + fileName;

                    Log.e("======file path========>",filePath);


                    if (FileUtil.createFile(filePath)) {
                        // 将图片保存在文件夹中
                        if (FileUtil.writeBitmapToSDCard(filePath,headBitmap)){

                            map = new HashMap<String, String>();
                            map.put("key","2");
                            map.put("value","");
                            map.put("file",filePath);

                            path = filePath;
                            Log.e("path ====file =====",path);

                            Message msg = new Message();
                            msg.what = HANDLER_DATA_NEED_RESET;
                            handler.sendMessage(msg);

                        }
//										ToastCustom.showToast(getApplicationContext(), "保存成功");
                    }

                }
                else
                    ToastCustom.showToast(getApplicationContext(), "无法获取图片，请重新选择");


            }
        }

        if (requestCode == ImageUtil.IMAGE_FROM_FILE) {//打开文件夹获取图片
            if (resultCode == RESULT_OK) { // 成功
                try {
                    Uri uri=data.getData();
                    Cursor cursor=getContentResolver().query(uri, null, null, null, null);
                    cursor.moveToFirst();
                    path=cursor.getString(1);
                    cursor.close();
                    if(path != null){
                        headBitmap = PictureFromCammera.scaleBitmap(path);
//                        head.setImageBitmap(headBitmap);
                        String fileName = FileUtil.headName;
                        String filePath = FileUtil.PHONE_DIR_INNER + FileUtil.PICTURE
                                + fileName;
                        Log.e("======file path========>",filePath);

                        if (FileUtil.createFile(filePath)) {
                            // 保存到手机sd卡中，同时缩小图片大小
                            if (FileUtil.writeBitmapToSDCard(filePath,headBitmap)){
                                map = new HashMap<String, String>();
                                map.put("key","2");
                                map.put("value","");
                                map.put("file",filePath);
                                path = filePath;

//                                Bitmap bitmap = BitmapFactory.decodeFile(filePath);
//

                                Message msg = new Message();
                                msg.what = HANDLER_DATA_NEED_RESET;
                                handler.sendMessage(msg);
                            }
//										ToastCustom.showToast(getApplicationContext(), "保存成功");
                        }
                    }
                    else
                        ToastCustom.showToast(getApplicationContext(), "无法保存图片，请重新选择");
                } catch (Exception e)
                {
                    ToastCustom.showToast(getApplicationContext(), "无法找到图片，请重新选择");
                }
            }
        }

        if(requestCode == RESOULT_RETURN){//设置activity成功返回来的数据

            if(resultCode == RESULT_OK){//证明操作成功,相应的内容

                Message msg = new Message();
                msg.what = data.getIntExtra("what",999);
                msg.arg1 = data.getIntExtra("arg1",999);
                msg.obj = data.getStringExtra("obj");
                handler.sendMessage(msg);

                Log.e("==============>",msg.what +"  "+msg.arg1 +"  " + msg.obj.toString());

            }
        }

        if(requestCode == RESOULT_UP_MASTER){

            if(resultCode == RESULT_OK){//创建店铺成功

                Log.e("==============>", "升级成点店主成功！");
//                role.setText("理发师");
//                user.setRole("理发师");


            }

        }

        if(requestCode == RESOULT_UP_HAIRRESET){

            if(resultCode == RESULT_OK){//升级成理发师成功

                Log.e("==============>","升级成理发师成功！");

                role.setText("理发师");
                user.setRole("理发师");


                //更改好友列表
                FriendList friendList = new FriendList();

                friendList.getFriendList(SocialListViewAdapter.getFriendListHandler, getApplicationContext());

            }

        }

    }


    class PersonlMessageHandler extends Handler {
        @Override
        public void dispatchMessage(Message msg) {

            switch (msg.what){

                case HANDLER_DATA_NEED_RESET://图片，性别等点击改变后需要提交到服务器

                    Log.d("===========>","提交到服务器改变性别");
                    if(!isSetting){
                        HttpUtil.apiResetPersonMessage(map,handler);
                        progressBar.setVisibility(View.VISIBLE);
                    }

                    break;

                case HANDLER_DATA_RESET:
                    break;

                case HttpUtil.RESET_PERSONAL_MESSAGE_SUCCESS:

                    switch (msg.arg1){

                        case 1://修改了昵称
                            nickName.setText(msg.obj.toString());
                            user.setNickname(msg.obj.toString());
                            break;
                        case 2://修改了头像

                            user.setHead(path);

                            Log.e("============>",user.getHead());
                            if(headBitmap != null)
                            head.setImageBitmap(headBitmap);
//                            imageLoader.displayImage(user.getHead(),head,ImageLoaderApi.getOptions());
                            path = "";
                            break;
                        case 3://修改了性别
                            gender.setText(msg.obj.toString());
                            user.setSex(msg.obj.toString());
                            break;
                        case 4://修改了个性签名
                            say.setText(msg.obj.toString());
                            user.setSignature(msg.obj.toString());
                            break;
                        case 5://修改了名字
                            name.setText(msg.obj.toString());
                            user.setName(msg.obj.toString());
                            break;
                        case 6://修改了地址
                            address.setText(msg.obj.toString());
                            user.setAddress(msg.obj.toString());
                            break;
                        case 7://修改了年龄
                            age.setText(msg.obj.toString());
                            user.setAge(msg.obj.toString());
                            break;

                    }
                    isSetting = false;
                    progressBar.setVisibility(View.GONE);

                    break;

                case HttpUtil.RESET_PERSONAL_MESSAGE_FAILD:

                    isSetting = false;
                    progressBar.setVisibility(View.GONE);
                    ToastCustom.showToast(getApplicationContext(),"网络异常，请稍后再试");

                    break;

                case HttpUtil.LOGIN_SUCCESS:

                    HttpUtil.reLogin(getApplicationContext(),handler);

                    break;

                case HttpUtil.LOGIN_FAILD:

                    isSetting = false;
                    progressBar.setVisibility(View.GONE);
                    ToastCustom.showToast(getApplicationContext(),"网络异常，请稍后再试");
                    break;

            }

        }
    }

    void setQRImage(){

        QRCode qrCode = new QRCode();
        Bitmap qrBitmap;
        if(User.getInstance() != null  && !User.getInstance().getId().equals("未登录")){//先看一下是否登录了

            JSONObject user = new JSONObject();
            try{
                user.put("ID",User.getInstance().getId());
                user.put("USER_ACCOUNT",User.getInstance().getPhone());
                user.put("NICK_NAME",User.getInstance().getNickname());

            }catch (Exception e){
                e.printStackTrace();
                Log.e("===========用户信息转json时出错========",e.getMessage());
            }

            qrBitmap = qrCode.createQRImage(user.toString());
            qrImage.setImageBitmap(qrBitmap);
            qrImage.setVisibility(View.VISIBLE);

        }else if(User.getUserInfo(getApplicationContext())  && !User.getInstance().getId().equals("未登录")){//没有登录就看一下配置文件
            System.out.println("查找数据成功");
            qrBitmap = qrCode.createQRImage(User.getInstance().toString());
            qrImage.setImageBitmap(qrBitmap);
            qrImage.setVisibility(View.VISIBLE);
        }else//都没有就不显示二维码
        {
            System.out.println("无法读入数据");
            nickName.setText("未登录");
            qrImage.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onDestroy() {

        User.saveUserInfo(getApplicationContext());

        super.onDestroy();
    }
}
